package com.platform.module.user.service.impl;

import com.platform.module.common.constant.CacheConstant;
import com.platform.module.common.redis.CacheClient;
import com.platform.module.common.utils.TokenGenerator;
import com.platform.module.dao.entity.TokenRecord;
import com.platform.module.pojo.UserRecord;
import com.platform.module.dao.mapper.TokenMapper;
import com.platform.module.user.service.TokenService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Long
 * @since 2024/11/14 15:13
 **/
@Slf4j
@Service
public class TokenServiceImpl implements TokenService {


    @Value("${token.key}")
    private String tokenKey;

    @Resource
    private CacheClient cacheClient;
    @Resource
    private TokenMapper tokenMapper;

    @Override
    public int updateStateLogout(Long userId) {
        this.cacheClient.removeKey(CacheConstant.USER_LOGIN_TOKEN + userId);
        this.cacheClient.removeKey(CacheConstant.USER_LOGIN_COOKIEKEY + userId);
        List<TokenRecord> list = this.tokenMapper.findTokenListByUserIdAndState(userId, 0);

        for (TokenRecord token : list) {
            this.tokenMapper.updateTokenStateById(token.getId());
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public TokenRecord generateNewToken(UserRecord user, String prefix) {
        String accessToken = TokenGenerator.createToken(user.getUserId() + "", tokenKey);
        TokenRecord tbToken = new TokenRecord();
        tbToken.setCaccesstoken(accessToken);
        tbToken.setIexpiresin(1209600000L);
        tbToken.setUserId(user.getUserId());
        int res = this.tokenMapper.addToken(tbToken);
        if (res != 1) {
            log.error("注册token失败,token：{},user:{} ", tbToken, user);
            throw new RuntimeException("注册token失败 ");
        } else {
            log.info("注册新token成功,uid:{}", user.getUserId());
            return tbToken;
        }
    }
}
